<?php
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;
use Admin\Controller\ContactController;

/**
 * 单位信息管理
 * Class PrepayController
 * @package Admin\Controller
 */
class PrepayController extends BaseController {
    /**
     * 系统管理 -> 系统管理 -> 单位信息维护 -> listview
     */
    public function index(){
        //获取搜索条件
        $filter = $this->fn_GenerateFilter();
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();

        //分页信息
        $pageNum = intval(I("post.page"));
        $pageNum = $pageNum==0?1:$pageNum;
        $page = $this->fn_GetPageInfo($where, $pageNum);
        $this->assign("page", $page);

        //搜索出单位信息
        $limit = ($page['from']-1).",".$page['num'];
        $list = M("prepay")->where($where)->order($order)->limit($limit)->select();
        for($i=0; $i<count($list); $i++){
            $list[$i]["offset"] = $page['from']-1+$i;
            if($list[$i]["sfjf"]=="否"){
                $list[$i]["qfts"] = self::dateDiff(date("Y/m/d"), $list[$i]["contact_jsrq"]);
                $list[$i]["qfje"] = round($list[$i]["qfts"]*$list[$i]["mzj"]/30, 2);
            }
        }
        $this->assign("list", $list);

        //设置搜索条件
        $this->assign("filter", $filter);
        $this->display();
    }

    /**
     * 单位信息维护 -> formview
     */
    public function detail(){
        //读取单位信息
        $dataId = I("get.id");
        $prepay = M("prepay")->where(array("id"=>$dataId))->find();
        $this->assign("prepay", $prepay);
        $this->assign("plog", $this->fn_GetPrepayLog($prepay['id']));

        //查询条件
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $pageInfo = $this->fn_GetPageInfo($where);

        //页面信息
        $offset = intval(I("get.offset"));
        $nearby = $this->fn_FindNearbyItems($where, $order, $offset);
        $page = array_merge($pageInfo, $nearby);
        $this->assign("page", $page);

        // 设置上下文信息
        $context = $this->fn_GenerateContext($page);
        $this->assign("context", $context);

        $this->display();
    }

    protected function fn_GetPrepayLog($preId){
        $where = array("prepay_id"=>$preId);
        return M("prepay_log")->where($where)->select();
    }

    /**
     * 单位信息维护 -> 新增
     */
    public function add(){
        if(IS_POST){    //添加公司信息
            $where = array(
                "name" => I("post.name"),
                "idno" => I("post.idno"),
                "state" => array("in", array('已提交', "待提交")),
            );
            $prepay = M("prepay")->where($where)->find();
            if($prepay){
                $this->error("操作失败，该住户尚有未抵扣完预缴租金");
            }

            $data = array(
                "name" => I("post.name"),
                "house_addr" => I("post.house_addr"),
                "date1" => I("post.date1"),
                "date2" => I("post.date2"),
                "phone" => I("post.phone"),
                "idno" => I("post.idno"),
                "amount" => I("post.amount"),
                "amount_left" => I("post.amount"),
                "pdate" => I("post.pdate"),
                "remarks" => I("post.remarks"),
                "state" => "待提交",
                "cuser" => session("username"),
                "ctime" => time(),
            );
            $dataId = M("prepay")->add($data);
            if($dataId){
                header("Location:/admin/prepay/detail?id=".$dataId);
            }else{
                $this->error("系统错误，预缴租金创建失败");
            }
        }

        //复制信息时处理流程
        if(I("get.id") && I("get.action"=="copy")){
            $prepay = M("prepay")->where(array("id"=>I("get.id")))->find();
            $this->assign("prepay", $prepay);
        }

        $this->display();
    }

    public function ajax_exit(){
        $dataId = I("post.id");
        $prepay = M("prepay")->where(array("id" => $dataId))->find();
        if(!$prepay){
            $this->error("参数错误");
        }

        $data = array("state"=>"已退款", "utime"=>time());
        $res = M("prepay")->where(array("id" => $dataId))->save($data);
        if(!$res){
            $this->error("系统异常，未知错误");
        }
        $this->success("操作成功");
    }

    public function ajax_submit(){
        $dataId = I("post.id");
        $prepay = M("prepay")->where(array("id" => $dataId))->find();
        if(!$prepay){
            $this->error("参数错误");
        }

        $data = array("state"=>"已提交", "invoice"=>I("post.invoice"));
        $res = M("prepay")->where(array("id" => $dataId))->save($data);
        if(!$res){
            $this->error("系统异常，未知错误");
        }
        $this->success("操作成功");
    }

    /**
     * AJAX方法，在listview中进行批量删除信息
     */
    public function ajax_del_abort(){

        $dataIds = I("post.info");
        if(count($dataIds)==0){
            $this->error("您还没有选中任何记录");
        }

        $map["id"] = array("in", $dataIds);
        $res = M("prepay")->where($map)->delete();
        if($res){
            $this->success("操作成功");
        }else{
            $this->error("系统错误");
        }
    }

    /**
     * AJAX方法，在formview中进行单条信息删除
     */
    public function ajax_del2(){
        //根据ID删除单位记录
        $id = I("post.id");
        $prepay = M("prepay")->where(array("id" => $id))->find();
        if(!$prepay){
            $this->error("参数错误");
        }

        if($prepay['state']!='待提交'){
            $this->error("操作失败，已提交信息无法删除");
        }

        $res = M("prepay")->where(array("id" => $id))->delete();
        if(!$res){
            $this->error("系统错误");
        }

        //分页信息
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $total = $this->fn_GetTotalItems($where);
        if($total==0){
            $this->success(null);
        }

        //计算下一条记录的offset
        $offset = intval(I("post.offset"));
        $offset = ($offset>=$total-1)?0:$offset;

        //获取下一记录的信息
        $nextItem = $this->fn_GetInfoByOffset($offset, $where, $order);
        $this->success($nextItem["id"]); //返回下一条记录的ID
    }

    /**
     * AJAX方法，通过ID来修改信息
     */
    public function ajax_UpdateInfoById(){
        $data = I("post.data");
        $dataId = I("post.id");
        $res = M("prepay")->where(array("id"=>$dataId))->save($data);
        if($res){
            $this->success("0k, 200");
        }else{
            $this->error("更新异常，请稍候再试");
        }
    }

    /**
     *  辅助方法，通过$_POST的值来生成where查询条件
     */
    private function fn_GenerateWhereClause(){
        $where = array();
        if(I("request.value")){
            $where[I("request.field")] = array("like", "%".I("request.value")."%");
        }
        return $where;
    }

    /**
     * 房屋自动补全搜索算法
     */
    public function ajax_SearchHouseByAddr(){
        $h = array();
        $where = array("h.addr"=>array("like", "%".I("get.house_addr")."%"));
        $house = M("house h")->where($where)->field("h.id, h.size,h.yw_no, h.addr, c.dibaork, c.type,
            c.community, h.name, c.zj, c.mzj, c.no as contact_no, c.zj, h.zhname, h.zhidno, h.phone")
            ->join(C("DB_PREFIX")."contact c on c.fwbh = h.name and c.yfsfz = h.zhidno", "LEFT")
            ->limit(10)->select();
        //$this->error(M()->getLastSql());
        foreach ($house as $v){
            array_push($h, array("value"=>$v["addr"], "data"=>$v));
        }
        $this->ajaxReturn(array('query'=>I("get.house_addr"), 'suggestions' => $h));
    }

    /**
     *  辅助方法，通过$_POST的值来生成order by子句
     */
    private function fn_GenerateOrderBy(){
        $order = "id desc";
        if(I("request.order_field") && I("request.order_sort")){
            $order = I("request.order_field") . " " . I("request.order_sort");
        }
        return $order;
    }

    /**
     *  辅助方法，通过$_POST的值来生成Filter (listview)
     */
    private function fn_GenerateFilter(){
        if(IS_POST){
            return array(
                "page" => I("post.page"),
                "field" => I("post.field"),
                "value" => I("post.value"),
                "order_field" => I("post.order_field"),
                "order_sort" => I("post.order_sort"),
            );
        }
        return array(
            "page" => 1,
            "order_field" => "id",
            "order_sort" => "desc",
        );
    }

    /**
     * 辅助方法，通过$_POST的值来生成Context (formvier)
     * @return array
     */
    private function fn_GenerateContext($page){
        return array(
            "id" => I("request.id"),
            "field" => I("request.field"),
            "value" => I("request.value"),
            "order_field" => I("request.order_field"),
            "order_sort" => I("request.order_sort"),
            "page" => I("request.page"),
            "offset" => I("request.offset"),
            "index" => I("get.offset")-($page["curPage"]-1)*$page["num"]+1
        );
    }

    /**
     * 辅助方法，通过where,order,offset来查询信息
     * @param $offset
     * @param $where
     * @param $order
     * @return mixed
     */
    private function fn_GetInfoByOffset($offset, $where, $order){
        $limit = $offset.",1";
        $res =  M("prepay")->field("id,name")->where($where)->order($order)->limit($limit)->select();
        if($res){
            return $res[0];
        }
        return array();
    }

    /**
     * 辅助方法，通过where, curpage, num来生成分页信息
     * @param $where
     * @param int $curPage
     * @param int $num
     * @return array
     */
    private function fn_GetPageInfo($where, $curPage=1, $num=15){
        $total = M("prepay")->where($where)->count();
        $totalPage = ceil($total/$num);
        $nextPage = $curPage==$totalPage?1:($curPage+1);
        $prevPage = $curPage==1?$totalPage:($curPage-1);
        $to = $curPage*$num;
        $res = array(
            "total" => $total,
            "num" => $num,
            "from" => (($curPage-1)*$num+1),
            "to" => $to>$total?$total:$to,
            "curPage" => $curPage,
            "nextPage" => $nextPage,
            "prevPage" => $prevPage
        );
        return $res;
    }

    /**
     * 辅助方法，通过where来统计总的信息数量
     * @param array $where
     * @return mixed
     */
    public function fn_GetTotalItems($where=array()){
        return M("prepay")->where($where)->count();
    }

    /**
     * 辅助方法，通过where, order, offset查询相邻两条数据
     * @param $where
     * @param $offset
     */
    public function fn_FindNearbyItems($where, $order, $offset){
        $total = M("prepay")->where($where)->count();
        $prevOffset = $offset>0?$offset-1:$total-1;
        $nextOffset = $offset>=$total-1?0:$offset+1;
        $prevItem = $this->fn_GetInfoByOffset($prevOffset, $where, $order);
        $nextItem = $this->fn_GetInfoByOffset($nextOffset, $where, $order);
        return array(
            "prev" => array("id"=>$prevItem["id"],"offset"=>$prevOffset),
            "next" => array("id"=>$nextItem["id"],"offset"=>$nextOffset),
        );
    }

    /**
     * 导出摇号中奖名单：
     * 1.如果选中了某些行，则导出所选中的项；
     * 2.如果没有选中任意行，则导出所有的项；
     */
    public function export(){
        $where = array("state"=>"未缴");
        $ids = I("get.ids");
        if($ids){
            $where = "id in (".$ids.")";
        }else if(I("get.field") & I("get.value")){
            $where[I("get.field")] = array("like", "%".I("get.value")."%");
        }
        $this->assign("where", serialize($where));
        $this->display();
    }

    /**
     * 导出公示名单
     * @throws \Exception
     */
    public function ajax_Exportprepay(){
        $where = unserialize( html_entity_decode(I("post.where")) ); //"被转换成了html实体，需要decode
        $data = M("prepay")->where($where)->order("house_no asc")->select();
        $fileName = $this->fn_ExportprepayExcel($data);
        $this->success($fileName);
    }

    public function fn_ExportprepayExcel($data){
        import("Common.ORG.Util.PHPExcel");
        import("Common.ORG.Util.PHPExcel.Writer.Excel5");
        import("Common.ORG.Util.PHPExcel.IOFactory.php");

        $inputFileName = "./db/xlsx_tpl/prepay.xls";
        try { //  Read your Excel workbook
            $inputFileType = \PHPExcel_IOFactory::identify($inputFileName);
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($inputFileName);
        } catch(Exception $e) {
            die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
        }

        $rowCount = 3; //从第2行开始写数据
        for($i=0; $i<count($data); $i++){
            $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, " ".$data[$i]["house_no"]);
            $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, " ".$data[$i]["name"]);
            $objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, " ".$data[$i]["idno"]);
            $objPHPExcel->getActiveSheet()->SetCellValue('D'.$rowCount, " ".$data[$i]["phone"]);
            $objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowCount, " ".$data[$i]["year"]);
            $objPHPExcel->getActiveSheet()->SetCellValue('F'.$rowCount, " ".$data[$i]["total"]);
            $objPHPExcel->getActiveSheet()->SetCellValue('G'.$rowCount, "年审".$data[$i]["state_ns"]);
            $rowCount += 1;
        }

        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $newFile = '/db/export/'.time().'.xlsx';
        $objWriter->save(".".$newFile);
        return $newFile;
    }

}